package org.dromara.finance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.finance.domain.Customer;
import org.dromara.finance.domain.Staff;
import org.dromara.finance.domain.SupplierCategory;
import org.dromara.finance.mapper.SupplierCategoryMapper;
import org.dromara.finance.utils.ContractReferenceCheckUtil;
import org.springframework.stereotype.Service;
import org.dromara.finance.domain.bo.SupplierBo;
import org.dromara.finance.domain.vo.SupplierVo;
import org.dromara.finance.domain.Supplier;
import org.dromara.finance.mapper.SupplierMapper;
import org.dromara.finance.service.ISupplierService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 供应商Service业务层处理
 *
 * @author xxy
 * @date 2025-08-15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SupplierServiceImpl implements ISupplierService {

    private final SupplierMapper baseMapper;

    private final SupplierCategoryMapper supplierCategoryMapper;
    private final ContractReferenceCheckUtil contractReferenceCheckUtil;

    /**
     * 查询供应商
     *
     * @param id 主键
     * @return 供应商
     */
    @Override
    public SupplierVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询供应商列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 供应商分页列表
     */
    @Override
    public TableDataInfo<SupplierVo> queryPageList(SupplierBo bo, PageQuery pageQuery) {
        QueryWrapper<Supplier> qw = buildQueryWrapper(bo);
        Page<SupplierVo> result = baseMapper.selectPageList(pageQuery.build(), qw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的供应商列表
     *
     * @param bo 查询条件
     * @return 供应商列表
     */
    @Override
    public List<SupplierVo> queryList(SupplierBo bo) {
        QueryWrapper<Supplier> qw = buildQueryWrapper(bo);
        return baseMapper.selectExportList(qw);
    }

    private QueryWrapper<Supplier> buildQueryWrapper(SupplierBo bo) {
        QueryWrapper<Supplier> qw = new QueryWrapper<>();
        qw.orderByAsc("s.id");
        qw.eq(StringUtils.isNotBlank(bo.getCode()), "s.code", bo.getCode());
        qw.like(StringUtils.isNotBlank(bo.getName()), "s.name", bo.getName());
        qw.eq(bo.getCategoryId() != null, "s.category_id", bo.getCategoryId());
        qw.eq(bo.getSupplierStatus() != null, "s.supplier_status", bo.getSupplierStatus());
        return qw;
    }


    /**
     * 新增供应商
     *
     * @param bo 供应商
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SupplierBo bo) {
        Supplier add = MapstructUtils.convert(bo, Supplier.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改供应商
     *
     * @param bo 供应商
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SupplierBo bo) {
        Supplier update = MapstructUtils.convert(bo, Supplier.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Supplier entity){
        //TODO 做一些数据校验,如唯一约束
        QueryWrapper<Supplier> wrapper = new QueryWrapper<>();
        wrapper.eq("code", entity.getCode());

        // 如果是修改，排除自身
        if (entity.getId() != null) {
            wrapper.ne("id", entity.getId());
        }

        Long count = baseMapper.selectCount(wrapper);
        if (count != null && count > 0) {
            throw new RuntimeException("供应商编码已存在");
        }
        // 校验 name 唯一性
        QueryWrapper<Supplier> nameWrapper = new QueryWrapper<>();
        nameWrapper.eq("name", entity.getName());
        if (entity.getId() != null) {
            nameWrapper.ne("id", entity.getId());
        }
        Long nameCount = baseMapper.selectCount(nameWrapper);
        if (nameCount != null && nameCount > 0) {
            throw new RuntimeException("供应商名称已存在");
        }
        if (entity.getSupplierStatus() == 1) {
            SupplierCategory supplierCategory = supplierCategoryMapper.selectById(entity.getCategoryId());
            if (supplierCategory.getSupplierCategoryStatus() == 2) {
                throw new RuntimeException("该供应商所在分类已停用,禁止启用!");
            }
        }
    }

    /**
     * 校验并批量删除供应商信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
            contractReferenceCheckUtil.checkReferenceArchive("purchase_contract", "supplier_id", ids, "供应商");
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
